Page({
  data: {
    dataList: [],    // 当前已展示的数据
    pageNo: 1,       // 当前页码
    pageSize: 10,    // 每页条数
    loading: false,  // 是否正在加载
    hasMore: true    // 是否还有更多数据
  },

  // 获取一页数据
  getPageData(callback) {
    const { pageNo, pageSize, dataList } = this.data;
    this.setData({ loading: true });
    wx.request({
      url: 'http://localhost:8080/article/put',
      data: { pageNo, pageSize },
      method: 'GET',
      success: (resp) => {
        const data = resp.data.data || {};
        let list = Array.isArray(data.list) ? data.list : [];
        // 只保留审核通过的文章
        list = list.filter(item => item.articleStatus === 1);
        // 处理图片路径
        list.forEach(item => {
          if (item.articlePic && !/^https?:\/\//.test(item.articlePic)) {
            item.articlePic = 'http://localhost:8080' + item.articlePic;
          }
        });
        // 合并数据
        const newDataList = dataList.concat(list);
        // 判断是否还有更多
        const hasMore = newDataList.length < (data.total || 0);
        this.setData({
          dataList: newDataList,
          hasMore,
          loading: false
        }, () => {
          if (callback) callback();
        });
      },
      fail: () => {
        this.setData({ loading: false });
      }
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({ dataList: [], pageNo: 1, hasMore: true });
    this.getPageData(() => {
      wx.stopPullDownRefresh();
    });
  },

  // 页面加载
  onLoad() {
    this.setData({ dataList: [], pageNo: 1, hasMore: true });
    this.getPageData();
  },

  // 触底加载更多
  onReachBottom() {
    if (!this.data.hasMore || this.data.loading) return;
    this.setData({ pageNo: this.data.pageNo + 1 }, () => {
      this.getPageData();
    });
  },

  // 跳转详情
  goToDetails(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/index/pages/articleDetails/articleDetails?id=${id}`
    });
  }
});